import requests
import json

zabbix_api = "http://192.168.189.142/zabbix/api_jsonrpc.php"
zabbix_user = "Admin"
zabbix_passwd = "zabbix"

# 用户登录，获取令牌
def getUserToken():
    data = {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": zabbix_user,
            "password": zabbix_passwd
        },
        "id": 1,
    }
    head = {"Content-Type":"application/json"}
    res = requests.post(url=zabbix_api, data=json.dumps(data), headers=head)
    user_token = json.loads(res.text).get("result")
    return user_token


# 获取被监控机的ip
def getHostID():
    user_token = getUserToken()
    data = {
           "jsonrpc": "2.0",
           "method": "host.get",
           "params": {
               "output": [
                   "hostid",
                   "host"
               ],
               "selectInterfaces": [
                   "interfaceid",
                   "ip"
               ]
           },
           "id": 2,
           "auth": user_token
    }
    head = {"Content-Type":"application/json"}
    res = requests.post(url=zabbix_api, data=json.dumps(data), headers=head)
    host_id = json.loads(res.text).get("result")[1].get("hostid")
    interface_id = json.loads(res.text).get("result")[1].get("interfaces")[0].get("interfaceid")
    return host_id, interface_id

# 添加监控项
def addITEM():
    user_token = getUserToken()
    host_id, interface_id = getHostID()
    data = {
           "jsonrpc": "2.0",
           "method": "item.create",
           "params": {
               "name": "磁盘/boot分区的剩余空间",
               "key_": "vfs.fs.size[/boot,free]",
               "hostid": host_id,
               "type": 0,
               "value_type": 3,
               "interfaceid": interface_id,
               "delay": 30
           },
           "auth": user_token,
           "id": 3
    }
    head = {"Content-Type":"application/json"}
    res = requests.post(url=zabbix_api, data=json.dumps(data), headers=head)
    if "error" in res.text:
        print("添加监控项失败")
    else:
        print("添加监控项成功")

if __name__ == '__main__':
    a = getUserToken()
    print(a)